package order

import (
	"fmt"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"go-papers/constant"
	"go-papers/logic"
	"go-papers/models/protocols"
	"go-papers/pkg/lognew"
	"go-papers/tools/helps"

	"go-papers/models"
	"go-papers/tools"
	"go-papers/tools/app"
	"go-papers/tools/app/msg"
)

func GetOrderList(c *gin.Context) {
	var data models.Order
	var err error
	var pageSize = 10
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}
	data.StatusType = c.Request.FormValue("statusType")
	data.OrderNo = c.Request.FormValue("orderNo")
	data.OrderName = c.Request.FormValue("orderName")
	data.OrderStatus = c.Request.FormValue("orderStatus")
	data.MemberId = tools.GetMemberId(c)
	if data.MemberId == 0 {
		app.CommonResp(c, 126, "请登陆后操作", nil)
		return
	}
	data.PayType = c.Request.FormValue("payType")
	data.PayNo = c.Request.FormValue("payNo")
	data.PayTime = c.Request.FormValue("payTime")

	result, count, err := data.GetMemberPage(pageSize, pageIndex)
	if err != nil {
		tools.HasError(err, "异常:"+err.Error(), -1)
	}

	app.PageOK(c, result, count, pageIndex, pageSize, "")
}

func GetOrder(c *gin.Context) {
	var data models.Order
	data.MemberId = tools.GetMemberId(c)
	if data.MemberId == 0 {
		app.CommonResp(c, 126, "请登陆后操作", nil)
		return
	}
	data.OrderId, _ = tools.StringToInt(c.Request.FormValue("orderId"))
	data.OrderNo = c.Request.FormValue("orderNo")
	openId := c.Request.FormValue("openId")
	if data.OrderId == 0 && data.OrderNo == "" {
		app.CommonResp(c, -1, "请求参数错误/缺失订单信息", nil)
		return
	}

	result, err := data.GetByOrderNo()
	if err != nil {
		app.ApiResp(c, -2, "抱歉未找到相关信息："+err.Error(), nil)
		return
	}

	res := make(map[string]interface{})
	res["order_info"] = result
	var orderPay models.OrderPay
	orderPay.OrderId = result.OrderId
	res["order_pay"] = orderPay.GetList()
	var orderStudent models.OrderStudent
	orderStudent.OrderId = result.OrderId
	res["order_student"] = orderStudent.GetList()
	var courseIn models.Course
	res["order_course"], _ = courseIn.GetByIdV2(result.CourseId, data.MemberId, openId)
	var refund models.OrderRefund
	refund.OrderId = result.OrderId
	res["order_refund"], _ = refund.GetList()
	var organ models.Organ
	res["organInfo"], _ = organ.GetByID(result.OrganId)

	app.OK(c, res, "")
}

func InsertOrder(c *gin.Context) {
	var pp protocols.OrderReq
	err := c.ShouldBindJSON(&pp)
	if err != nil {
		app.ApiResp(c, -1, "数据解析异常："+err.Error(), nil)
		return
	}

	lognew.Info(c, "InsertOrder", lognew.Fields{"pp": pp})

	//验证用户
	openId := pp.OpenId
	mid := tools.GetMemberId(c)
	if mid == 0 {
		app.CommonResp(c, 126, "请登陆后操作", nil)
		return
	}

	//验证课程id 是否为空
	var newids []int
	courseId := 0
	if len(pp.CourseIds) > 0 {
		for _, v := range pp.CourseIds {
			if v > 0 {
				courseId = v
				newids = append(newids, v)
				break
			}
		}
	}
	if len(newids) <= 0 {
		app.ApiResp(c, -1, "课程信息解析失败：", nil)
		return
	}

	// 查询机构信息
	var courseInfo models.Course
	courseNewInfo, _ := courseInfo.GetById(courseId)
	if courseNewInfo.OrganId == 0 {
		app.ApiResp(c, -1, "课程信息解析失败：", nil)
		return
	}

	var organ models.Organ
	organInfo, _ := organ.GetByID(courseNewInfo.OrganId)
	if organInfo.OrganPayAccount == "" {
		app.ApiResp(c, -1, fmt.Sprintf("该商户不支持在线支付 %d", courseNewInfo.OrganId), nil)
		return
	}

	//获取用户信息
	var mm models.Member
	mm.MemberId = mid
	memberInfo, _ := mm.Get()

	//计算价格
	now := time.Now().Format("20060102")
	randI := helps.RandInt(10000, 99999)
	randS := helps.RandString(3)
	orderNo := "U" + now + randS + strconv.Itoa(randI)

	data := models.Order{
		OrderNo:         orderNo,
		OrderName:       "下单",
		OpenId:          openId,
		OrderStatus:     constant.ORDER_STATUS_1,
		OrderStatusName: "下单",
		OrderPrice:      0,
		TotalPrice:      0,
		RefundPrice:     0,
		MemberId:        mid,
		MemberMomId:     memberInfo.MomUserId,
		MemberMomName:   memberInfo.MomRealName,
		MemberName:      memberInfo.NickName,
		MemberPhone:     memberInfo.Phone,
		PayAccount:      "",
		OrganPayAccount: organInfo.OrganPayAccount,
		OrganPayType:    organInfo.OrganPayType,
		CourseCover:     "",
		CourseId:        0,
		OrganId:         0,
		OrganName:       "",
		CourseName:      "",
		BrandName:       "",
		CreateTime:      time.Now().Format("2006-01-02 15:04:05"),
		PayType:         "wx",
		PayNo:           "",
		CloseReason:     "",
	}
	result, err := data.Create()
	if err != nil {
		app.CommonResp(c, -1, "订单创建失败："+err.Error(), nil)
		return
	}
	if result.OrderId == 0 {
		app.CommonResp(c, -1, "订单创建失败.", nil)
		return
	}

	orderId := result.OrderId

	//获取学生信息
	var ms models.MemberStudent
	studentInfo, err := ms.GetByID(pp.StudentId)
	if err != nil {
		app.CommonResp(c, -1, "下单学生信息未查询到.", nil)
		return
	}

	//生产
	ostu := models.OrderStudent{
		StudentId:      pp.StudentId,
		OrderId:        orderId,
		MemberId:       mid,
		StudentName:    studentInfo.StudentName,
		StudentAge:     studentInfo.StudentAge,
		StudentPhone:   studentInfo.StudentPhone,
		StudentAddr:    studentInfo.Province + " " + studentInfo.City + " " + studentInfo.Area + " " + studentInfo.Address,
		StudentAddress: studentInfo.Address,
		StudentGrade:   studentInfo.StudentGrade,
	}
	_, err = ostu.Create()
	if err != nil {
		lognew.Error(c, "orderStudentCreate", lognew.Fields{"data": ostu, "err": err.Error()})
	}
	//获取课程信息
	totalPrice := 0.0
	orderPrice := 0.0
	courseName := "订单"
	CourseId := 0
	organName := ""
	brandName := ""
	CourseCover := ""
	errmsg := ""
	organId := 0
	organMomId := 0
	organMomName := ""
	var organM models.Organ
	for _, v := range pp.CourseIds {
		courseInfo.CourseId = v
		cc, err := courseInfo.Get()
		if err != nil {
			errmsg = "课程信息未查询到。" + err.Error()
			break
		}
		CourseId = cc.CourseId
		courseName = cc.CourseName + "/" + cc.CourseCategory + "/" + cc.CourseType
		organName = cc.OrganName
		organId = cc.OrganId

		organInfo, _ := organM.GetByID(organId)
		organMomId = organInfo.OrganMomId
		organMomName = organInfo.OrganMomName
		brandName = cc.BrandName
		CourseCover = cc.CourseImg
		ll := cc.CoursePrice - cc.DiscountPrice
		if ll > 0 {
			orderPrice += ll
		}
		totalPrice += cc.CoursePrice

		// 订单 order_course
		orderCourse := models.OrderCourse{
			OrderId:         orderId,
			CourseId:        CourseId,
			MemberId:        mid,
			CoursePrice:     cc.CoursePrice,
			CoursePayPrice:  ll,
			CourseName:      courseName,
			CourseCode:      cc.CourseCode,
			CourseImg:       cc.CourseImg,
			CourseType:      cc.CourseType,
			CourseTeach:     cc.CourseTeach,
			CourseCategory:  cc.CourseCategory,
			CourseOrganName: cc.OrganName,
			CourseBrandName: cc.BrandName,
		}
		_, err = orderCourse.Create()
		if err != nil {
			lognew.Error(c, "orderCoruseCreate", lognew.Fields{"data": orderCourse, "err": err.Error()})
		}
		break
	}

	if errmsg != "" {
		app.ApiResp(c, -1, errmsg, nil)
		return
	}

	//订单价格
	result.OrderName = courseName
	result.TotalPrice = totalPrice
	result.OrderPrice = orderPrice
	result.CourseId = CourseId
	result.CourseName = courseName
	result.CourseCover = CourseCover
	result.OrganName = organName
	result.OrganId = organId
	result.OrganMomId = organMomId
	result.OrganMomName = organMomName
	result.BrandName = brandName
	result.PayNo = ""
	result.OrderStatus = constant.ORDER_STATUS_5
	result.PayType = "微信"
	_, _ = result.Update(orderId)

	//用户操作订单记录
	orlog := models.OrderOprateLog{
		OrderId:         orderId,
		Title:           "用户下单",
		Desc:            "用户下单/" + result.PayType + "/" + fmt.Sprintf("%.2f", result.OrderPrice),
		LogType:         "5",
		OrderStatusName: tools.OrderStatusName(result.OrderStatus),
		PayStatusName:   tools.PayStatusName(result.PayTime, result.RefundTime),
		LogName:         "用户下单",
		LogUid:          mid,
	}
	_, _ = orlog.Create() // 用户下单

	//生产支付订单
	wxPay, err := logic.GetPrepayId(c, result.OrderId, openId, false)

	resp := make(map[string]interface{})
	resp["orderId"] = result.OrderId
	resp["orderNo"] = result.OrderNo
	resp["orderName"] = result.OrderName
	if err != nil {
		resp["err_msg"] = err.Error()
	} else {
		resp["err_msg"] = ""
	}
	if wxPay != nil && wxPay.PrepayId != "" {
		resp["trade_type"] = wxPay.TradeType
		resp["prepay_id"] = wxPay.PrepayId
		resp["code_url"] = wxPay.CodeUrl

		payInfo := make(map[string]interface{})
		// 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。 但最新版的支付后台生成签名使用的timeStamp 字段名需大写其中的S字符
		payInfo["timeStamp"] = time.Now().Unix()
		payInfo["nonceStr"] = wxPay.NonceStr // 支付签名随机串，不长于 32 位
		// 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
		payInfo["package"] = "prepay_id=" + wxPay.PrepayId
		// 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
		payInfo["signType"] = "MD5"
		// 支付签名
		payInfo["paySign"] = logic.GetPaySign(payInfo, "wx")

		resp["pay_info"] = payInfo

		lognew.Info(c, "InsertOrder-Back", lognew.Fields{"pp": pp, "resp": resp})

	} else {
		resp["trade_type"] = ""
		resp["prepay_id"] = ""
		resp["code_url"] = ""
		resp["pay_info"] = nil

		lognew.Info(c, "InsertOrder-Back", lognew.Fields{"pp": pp, "resp": resp})

		app.OK(c, resp, "下单成功，去支付")
		return
	}

	app.OK(c, resp, "下单成功，去支付")
}

func UpdateOrder(c *gin.Context) {
	var data models.Order
	err := c.BindWith(&data, binding.JSON)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	data.MemberId = tools.GetMemberId(c)
	if data.MemberId == 0 {
		app.CommonResp(c, 126, "请登陆后操作", nil)
		return
	}

	result, err := data.Update(data.OrderId)
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	app.OK(c, result, "")
}

func DeleteOrder(c *gin.Context) {
	var data models.Order

	data.MemberId = tools.GetMemberId(c)
	if data.MemberId == 0 {
		app.CommonResp(c, 126, "请登陆后操作", nil)
		return
	}

	IDS := tools.IdsStrToIdsIntGroup("orderId", c)
	_, err := data.BatchDelete(IDS)
	if err != nil {
		app.ApiResp(c, -1, "数据删除失败："+err.Error(), nil)
		return
	}

	app.OK(c, nil, msg.DeletedSuccess)
}
